<template>
  <div style="display: flex; flex-grow: 1; flex-direction: column; overflow: auto; position: relative;">
    <div class="knowledge-base-container">
      <div class="knowledge-base-option">
        <el-select v-model="chatMode" placeholder="Select" size="small" class="mode-select">
          <el-option
              v-for="item in chatModeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
          />
        </el-select>
        <el-select v-model="knowledgeBase" placeholder="Select" size="small" class="mode-select">
          <el-option
              v-for="item in knowledgeBaseOptions"
              :key="item"
              :label="item"
              :value="item"
          />
        </el-select>
      </div>
      <div class="funcs-container">
        <SearchContainer v-if="chatMode==='search'" :searchResult="searchResult" :isSearching="isSearching" :searchQuery="searchQuery"/>
        <AIChat v-if="chatMode==='chat'" :history="history" :isGenerating="isGenerating"/>
      </div>
    </div>
    <div class="material-search">
      <el-tooltip content="知识库管理" placement="top">
        <div @click="centerDialogVisible=true" class="knowledge-base">
          <i class="iconfont icon-ic_wenjianjia"/>
        </div>
      </el-tooltip>
      <input type="text" autocomplete="off" :placeholder="(()=>{
          switch (chatMode){
            case 'search':
              return '检索知识库'
            case 'chat':
              return '请输入问题'
          }
      })()" v-model="searchText" @keydown.enter="search"/>
      <div @click="search" class="icon">
        <div class="iconfont icon-sousuo"/>
      </div>
    </div>
    <el-dialog v-model="centerDialogVisible" :show-close="false" width="50%" center style="border-radius: 12px;">
      <KnowledgeBases :knowledgeBases="knowledgeBaseOptions" @close="centerDialogVisible=false"
                      @deleteKnowledgeBases="deleteKnowledgeBases" @createKnowledgeBases="createKnowledgeBases" v-if="centerDialogVisible"/>
    </el-dialog>
  </div>
</template>

<script setup>
import {onUnmounted, reactive, ref, watch} from 'vue'
import { get } from '../utils/request.js'
import SearchContainer from './SearchContainer.vue'
import AIChat from './AIChat.vue'
import {generate} from '../utils/index.js'
import KnowledgeBases from './KnowledgeBases.vue'

const chatMode = ref('search') //search chat
const chatModeOptions = reactive([
  {
    label: '知识库检索',
    value: 'search'
  },
  {
    label: '知识库问答',
    value: 'chat'
  }
])
const centerDialogVisible = ref(false)
const searchText = ref('')
const genRes = ref('')
const search = ()=>{
  if(knowledgeBase.value !== '请选择知识库'){
    switch (chatMode.value){
      case 'search':
          searchResult.value = null
          isSearching.value = true
          searchQuery.value = searchText.value
          get('api/knowledge_base_search', { knowledge_base: knowledgeBase.value, query: searchText.value }).then(res=>{
            searchResult.value = res.data
            isSearching.value = false
          }).catch(()=>{
            isSearching.value = false
            searchQuery.value = ''
          })
          searchText.value = ''
        break
      case 'chat':
        if(!isGenerating.value){
          genRes.value = ''
          isGenerating.value = true
          history.value.push({
            role: 'me',
            message: searchText.value
          })
          history.value.push({
            role: 'ai',
            message: ''
          })
          generate('knowledge_base_chat', {text: searchText.value, knowledge_base: knowledgeBase.value},(e) => {
            genRes.value += e
          }, () => {
            isGenerating.value = false
          })
          searchText.value = ''
        }
        break
    }
  }else {
    ElMessage({
      message: '请选择知识库！',
      type: 'error',
    })
  }
}
let intervalId = null;
const isGenerating = ref(true)
watch(isGenerating,()=>{
  if (isGenerating.value) {
    let len = 0;
    let tmp_gen_len
    let last_gen_len = 0
    if (intervalId !== null) {
      clearInterval(intervalId);
    }
    intervalId = setInterval(() => {
      if (len < tmp_gen_len) {
        history.value[history.value.length - 1].message += genRes.value.slice(len, tmp_gen_len);
        len = tmp_gen_len;
      }
      if (len < genRes.value.length) {
        history.value[history.value.length - 1].message += genRes.value.slice(len, len + 1);
        len++;
      }
      if (genRes.value.length !== last_gen_len) {
        tmp_gen_len = last_gen_len
        last_gen_len = genRes.value.length
      }
    }, 100);
  }else{
    clearInterval(intervalId);
  }
})
onUnmounted(()=>{
  clearInterval(intervalId);
})
const isSearching = ref(false)
const searchResult = ref(null)
const searchQuery = ref('')
watch(chatMode,()=>{
  searchResult.value = null
  searchQuery.value = ''
  isSearching.value = false
  clearInterval(intervalId);
  history.value = []
  isGenerating.value = false
})
const history = ref([])

const knowledgeBase = ref('请选择知识库')
const knowledgeBaseOptions = ref([])
get('api/get_knowledge_base_list').then(e=>{
  knowledgeBaseOptions.value = e.data.data
})
const deleteKnowledgeBases = (knowledgeBaseName) => {
  knowledgeBaseOptions.value = knowledgeBaseOptions.value.filter(item => item !== knowledgeBaseName)
}
const createKnowledgeBases = (knowledgeBaseName) => {
  knowledgeBaseOptions.value.push(knowledgeBaseName)
  knowledgeBaseOptions.value = [...new Set(knowledgeBaseOptions.value)]
}
</script>

<style lang="scss" scoped>
:deep(.el-input.el-input--small.el-input--suffix){
  width: 10em;
}
:deep(.el-dialog__header){
  display:none;
}
:deep(.el-dialog__body){
  padding: 0;
}
.knowledge-base-container{
  flex-grow: 1;
  overflow: auto;
  display: flex;
  flex-direction: column;
  box-sizing: border-box;
  .knowledge-base-option{
    padding: 5px 0;
    border-bottom: 1px solid #dfdfdf;
    display: flex;
    .mode-select{
      margin-left: 5px;
    }
  }
  .funcs-container{
    overflow: auto;
    flex-grow: 1;
  }
}
.material-search{
  display: flex;
  padding: 10px 10px 10px 0;
  border-top: 1px solid #dfdfdf;
  .knowledge-base{
    cursor: pointer;
    display: flex;
    justify-content: center;
    align-items: center;
    height:40px;
    width: 40px;
    .icon-ic_wenjianjia{
      font-size: 1.5em;
    }
  }
  input[type="text"]{
    box-sizing: border-box;
    text-align:center;
    height:40px;
    border:1px solid #c8cccf;
    color:#6a6f77;
    display:block;
    outline:0;
    padding:0 1em;
    width:100%;
  }
  .icon{
    box-sizing: border-box;
    height:40px;
    width: 40px;
    border:1px solid #c8cccf;
    border-left: none;
    display: flex;
    justify-content: center;
    align-items: center;
    cursor: pointer;
  }
}
</style>
